<script setup lang="ts">
import {
  getApplicationsApi,
  updateApplicationApi,
} from '@/apis/modules/application'
import { useConfirm } from '@/composables/useConfirm'
import { Message } from '@arco-design/web-vue'
import { useConfig } from './useConfig'

const { tableColumns, queryParams } = useConfig()

const {
  data: tableData,
  loading,
  run,
} = useListRequest(getApplicationsApi, {
  immediate: true,
  params: queryParams,
})

const handleStatusChange = useConfirm<Recordable>(
  {
    title: '禁用应用',
    content: '确定要禁用应用吗？禁用后，应用的商品将无法新购和续费。',
    immediate: data => Number(data.status) === 2,
  },
  async (data) => {
    await updateApplicationApi({
      ...data,
      status: data?.status === 1 ? 2 : 1,
    })
    await run()
    Message.success('操作成功')
  },
)

// 编辑备注
async function handleSubmitRemark(data: any) {
  await updateApplicationApi(data)
  await run()
  Message.success('修改成功')
}
</script>

<template>
  <main-container
    :loading="loading"
    :pagination="false"
    @run="run"
  >
    <a-table
      v-bind="mergeTableProps({ rowKey: 'app_id' })"
      :data="tableData"
      :columns="tableColumns"
    >
      <template #name="{ record }">
        <!-- <div class="flex items-center space-x-3">
          <a-image
            :preview="false"
            class="size-12"
            :src="record.icon"
          />
        </div> -->
        <div class="flex flex-col items-start space-y-1.5">
          <strong> {{ record?.name }}</strong>
          <span class="text-color-3">ID: {{ record?.app_id }}</span>
        </div>
      </template>
      <template #status="{ record }">
        <a-switch
          size="small"
          :model-value="record.status === 1"
          @change="() => handleStatusChange(record)"
        />
      </template>
      <template #remark="{ record }">
        <edit-field
          edit-title="编辑备注"
          hover-table
          field="remark"
          placeholder="请输入备注"
          :max-length="20"
          :params="record"
          :required="false"
          :default-value="record.remark"
          :fn="handleSubmitRemark"
        >
          {{ record.remark }}
        </edit-field>
      </template>
      <template #action="{ record }">
        <router-link
          :to="{
            name: 'ApplicationsConfig',
            params: { appid: record?.app_id },
          }"
        >
          <a-button type="text">
            <template #icon>
              <i-icons-edit />
            </template>
          </a-button>
        </router-link>
      </template>
    </a-table>
  </main-container>
</template>

<style scoped></style>
